package net

import (
	"encoding/json"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v3/client"
	"github.com/alibabacloud-go/tea/tea"
)

/**
 * 使用AK&SK初始化账号Client
 * @param accessKeyId
 * @param accessKeySecret
 * @return Client
 * @throws Exception
 */
func CreateClient(accessKeyId *string, accessKeySecret *string) (_result *dysmsapi20170525.Client, _err error) {
	config := &openapi.Config{
		// 必填，您的 AccessKey ID
		AccessKeyId: accessKeyId,
		// 必填，您的 AccessKey Secret
		AccessKeySecret: accessKeySecret,
	}
	// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_result = &dysmsapi20170525.Client{}
	_result, _err = dysmsapi20170525.NewClient(config)
	return _result, _err
}

func AliyunSendSMS(accessKeyId, accessKeySecret, signName, templateCode, code, phone string) *dysmsapi20170525.SendSmsResponse {
	client, _err := CreateClient(&accessKeyId, &accessKeySecret)
	if _err != nil {
		return nil
	}
	bCode, _ := json.Marshal(map[string]interface{}{
		"code": code,
	})
	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		SignName:      tea.String(signName),
		TemplateCode:  tea.String(templateCode),
		TemplateParam: tea.String(string(bCode)),
		PhoneNumbers:  tea.String(phone),
	}
	sendSmsResponse, _err := client.SendSms(sendSmsRequest)
	if _err != nil {
		return nil
	}
	return sendSmsResponse
}
